﻿using Furion.DependencyInjection;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.CMS.Application.OuterEvent
{
    public class OuterEventHubManager : IOuterEventHub, ISingleton
    {
        /// <summary>
        /// 外部事件订阅注册存储
        /// </summary>
        private readonly ConcurrentDictionary<ListenerKey, OuterEventListenerProvider> OuterEventSubscriberStorer;

        public OuterEventHubManager()
        {
            OuterEventSubscriberStorer = new ConcurrentDictionary<ListenerKey, OuterEventListenerProvider>();
        }

        /// <summary>
        /// 给传入的用户ID注册事件监听
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public IOuterEventListener Register(string userId, Guid channelId)
        {
            return OuterEventSubscriberStorer.GetOrAdd(new ListenerKey(userId, channelId),
                (k) => new OuterEventListenerProvider(k, this));
        }

        public void UnRegister(string userId, Guid channelId)
        {
            OuterEventSubscriberStorer.TryRemove(new ListenerKey(userId, channelId), out var listeners);
        }

        public List<IOuterEventProvider> Get(string userId)
        {
            var listeners = OuterEventSubscriberStorer.Where(t => t.Key.UserId == userId)
                .Select(s => s.Value)
                .Cast<IOuterEventProvider>()
                .ToList();

            return listeners;
        }

        public List<IOuterEventProvider> GetAll()
        {
            return OuterEventSubscriberStorer.Values.Cast<IOuterEventProvider>().ToList();
        }
    }
}
